﻿using Gameplay.PVE;
using ImageEffects;
using System;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEngine;
using XLua;
using Yoozoo.Gta.Common;
using Yoozoo.Managers.ResourceManagerV2.Runtime;

namespace Modules.Guide.Runtime
{
    public class GuideSceneLoad : MonoBehaviour
    {
        [Serializable]
        public struct GudieScenePlayInfo
        {
            public string playPath;
            public Vector3 playPos;
            public Vector3 playScale;
            public Vector3 playAngles;
            public Transform parent;
            public string startAniName;
            public string startTrigger;
            public string name;
        }
   
        public List<GudieScenePlayInfo> playInfos = new List<GudieScenePlayInfo>();
        List<GameObject> playObjs = new List<GameObject>();
        ResLoader _resLoader;
        LuaFunction _luaCall;
        int loadNum = 0;
        int unLoadNum = 0;

        string defaultPath = "Assets/ResourcesAssets/Dialoague/Scene/{0}.prefab";
        LightController lightController;
        public void LoadPlays(LuaFunction luaCall)
        {
            // 加载所有场景对象
            _luaCall = luaCall;
            LoadPlay();
        }

        // 加载新手场景中模型
        void LoadPlay()
        {
            // 加载队列为空
            if (playInfos == null || playInfos.Count <= 0)
            {
                _luaCall?.Call();
                return;
            }
            // 加载完成
            if (loadNum >= playInfos.Count)
            {
                _luaCall?.Call();
                return;
            }
            // 逐个加载
            if (_resLoader == null) _resLoader = ResLoader.Alloc();
            if (lightController == null) lightController = gameObject.GetComponentInChildren<LightController>(true);
      
            _resLoader.Add2Load(playInfos[loadNum].playPath, (success, name, asset) =>
            {
                if (!success)
                {
                    UnityEngine.Debug.LogError("GuideSceneLoad load play err :" + name);
                }
                else
                {
                    GudieScenePlayInfo info = playInfos[loadNum];
                    GameObject obj = Instantiate(asset as GameObject);
                    obj.transform.SetParent(info.parent, false);
                    obj.transform.localScale = info.playScale;
                    obj.transform.eulerAngles = info.playAngles;
                    obj.name = info.name;
                    Animator ani = obj.GetComponent<Animator>();
                    if (ani)
                    {
                        if (info.startAniName != "")
                        {
                            ani.Play(info.startAniName);
                        }
                        if (info.startTrigger != "")
                        {
                            ani.SetTrigger(info.startTrigger);
                        }
                        ani.SetLayerWeight(ani.GetLayerIndex("Face Layer"), 1); //设置面部权重 
                    }

                    obj.transform.localPosition = info.playPos;
                    playObjs.Add(obj); // 记录已加载对象 用于卸载
                    //
                    LightElement lightElement = obj.GetComponent<LightElement>();
                    if (lightElement)
                    {
                        lightController.AddLightElement(lightElement);
                        lightElement.CloneMaterial = true;
                    }
                     
                    TimeManager.Instance.DelayCall(1, () =>
                    {
                        LoadPlay();
                    }, true);
                }
                loadNum++;
            }).Load();
        }

        public void UnLoadPlays(LuaFunction luaCall)
        {
            _luaCall = luaCall;
            UnLoadPlay();
        }
        // 卸载新手场景中模型
        void UnLoadPlay()
        {
            // 卸载完成
            if (unLoadNum >= loadNum || playObjs.Count <= 0)
            {
                _resLoader.Recycle2Cache();
                _resLoader = null;
                playInfos = null;
                _luaCall?.Call();
                return;
            }
            GameObject obj = playObjs[0];
            playObjs.RemoveAt(0);
            Destroy(obj);

            _resLoader.ReleaseRes(playInfos[unLoadNum].playPath, typeof(GameObject));
            GameHelper.ForceReleaseNoGC();
            unLoadNum++;
            TimeManager.Instance.DelayCall(20, () =>
            {
                UnLoadPlay();
            }, true);
        }

        public void SetPlayInfos()
        {
#if UNITY_EDITOR
            // 解绑预制体
            PrefabUtility.UnpackPrefabInstance(gameObject, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);
            // 记录数据
            Animator[] animators = gameObject.GetComponentsInChildren<Animator>();
            for (int i = 0; i < animators.Length; i++)
            {
                Animator animator = animators[i];
                if (animator == null || animator.gameObject.GetComponent<LightElement>() == null) continue;
                GudieScenePlayInfo info = new GudieScenePlayInfo();
                info.parent = animator.transform.parent;
                info.playAngles = animator.transform.eulerAngles;
                info.playPos = animator.transform.localPosition;
                info.playScale = animator.transform.localScale;
                info.name = animator.gameObject.name;
                // 可能存在的预制体名字
                info.startAniName = "";
                DialogueAniStart aniStart = animator.gameObject.GetComponent<DialogueAniStart>();
                if (aniStart)
                {
                    info.startAniName = aniStart.aniName;
                }
                // 可能存在的startTrigger
                info.startTrigger = "";
                if (aniStart)
                {
                    info.startTrigger = aniStart.aniTrigger;
                }
                // 路径
                GameObject parentObject = PrefabUtility.GetCorrespondingObjectFromSource(animator.gameObject);
                info.playPath = AssetDatabase.GetAssetPath(parentObject);
                playInfos.Add(info);
                DestroyImmediate(animator.gameObject);
            }
            // 生成运行时预制体
            string assetPath = string.Format(defaultPath, gameObject.name);
            PrefabUtility.SaveAsPrefabAssetAndConnect(gameObject, assetPath, InteractionMode.AutomatedAction);
#endif
        }
    }
}

